<template>
	<div ref="container">
		<div style="position: absolute; z-index: 10" class="flex-center w100 h100" v-show="loading">
			<dv-decoration :scale="2">
				<span class="fw" style="font-size: 30px"> {{ percentComplete }}% </span>
			</dv-decoration>
		</div>
		<my-compass :keyType="keyType" />
	</div>
</template>

<script setup name="tunnelling">
import { DBUtil } from '@u/indexedDB'
import { useResizeObserver, THREE, clock, GLTFloaderFn, rendererFn, cameraFn, TWEEN, cameraTwwen, compassRotate, keyType } from '@u/threeMinx'

let container = shallowRef(null), // 模型渲染的Demo节点
	renderer, //  WebGLRenderer渲染器
	scene, // 场景
	camera, // 相机
	cameraRender,
	loading = ref(false),
	percentComplete = ref(0)

// 组件宽高
let width, height
useResizeObserver(container, (entries) => {
	width = entries[0].contentRect.width
	height = entries[0].contentRect.height
	camera.aspect = width / height
	camera.updateProjectionMatrix()
	renderer.setSize(width, height)
})
// 初始化生命周期
onMounted(() => {
	loading.value = true
	init()
})
onBeforeUnmount(() => {
	cancelAnimationFrame(requestAnimationFrameIndex)
	// 释放显存
	renderer?.dispose()
	// 释放内存
	container = null
	scene = null
})

function init() {
	// 场景
	scene = new THREE.Scene()
	// 相机
	camera = new THREE.PerspectiveCamera(45, width / height, 1, 2000)
	camera.position.set(67, -3, 7.6)
	camera.lookAt(72, -4, 0)
	cameraRender = cameraFn(camera)
	scene.add(camera)
	renderer = rendererFn(container)
	// 加载器
	loaderFn()
}
let objects = [],
	mixers = [],
	model,
	// 所有的煤块
	group = new THREE.Group()

function loaderFn() {
	new DBUtil().get(`${import.meta.env.VITE_APP_BASE_BASE || '/'}model/掘进面.glb`).then((blob) => {
		let url = URL.createObjectURL(blob)
		GLTFloaderFn.load(
			url,
			function (object) {
				loading.value = false
				model = object.scene
				scene.add(model)
				objects = model.getObjectByName('矿道').children
				// 灯光
				lights()
				// // 煤块
				// group.position.set(85, -7.1, -4.5);
				// scene.add(group);
				// for (let i = 0; i < 20; i++) {
				//     for (let j = 1; j < 3; j++) {
				//         const coal = model.getObjectByName(`煤块${j}`).clone(),
				//             scale = Math.random() * 0.7 + 0.2;
				//         coal.position.set(-Math.random(), Math.random() * 3, Math.random() * 3);
				//         coal.scale.set(scale, scale, scale);
				//         coal.rotateX(scale);
				//         coal.rotateY(scale);
				//         coal.rotateZ(scale);
				//         group.add(coal);
				//     }
				// }

				// const coalTween = function (coal, { x, y, z }) {
				//     coal.position.set(x, y, z);
				//     new TWEEN.Tween(coal.position)
				//         .delay(Math.random() * 4000)
				//         .to(
				//             {
				//                 x: 61.541,
				//                 y: -5.335,
				//             },
				//             5000
				//         )
				//         .onComplete(() => {
				//             coalTween(coal, { x, y, z });
				//         })
				//         .start();
				// };
				// // 传送带上的煤块
				// for (let i = 0; i < 40; i++) {
				//     for (let j = 1; j < 3; j++) {
				//         const coal = model.getObjectByName(`煤块${j}`).clone(),
				//             scale = Math.random() * 0.2 + 0.05;
				//         coal.position.set(78.128, -8.054, -1.868 + Math.random() * 0.01);
				//         coal.scale.set(scale, scale, scale);
				//         coal.rotateX(scale);
				//         coal.rotateY(scale);
				//         coal.rotateZ(scale);
				//         scene.add(coal);
				//         coalTween(coal, coal.position);
				//     }
				// }
				//动画
				const animations = object.animations
				const mixer = new THREE.AnimationMixer(model)
				const actions = []
				for (var i = 0; i < animations.length; i++) {
					actions.push(mixer.clipAction(animations[i]))
				}
				actions.forEach((action) => {
					action.play()
				})
				mixers.push(mixer)
				// 视角动画
				setTimeout(() => {
					cameraTwwen({ camera, newP: { x: 45, y: -3, z: 4 }, newT: { x: 72, y: -3, z: -10 }, time: 5000 })
				}, 5000)
				// 渲染器
				render()
			},
			function (xhr) {
				if (xhr.lengthComputable) percentComplete.value = Math.round((xhr.loaded / xhr.total) * 100, 2)
			}
		)
	})
}
/**
 * 灯光
 */
function lights() {
	// 自然光
	scene.add(new THREE.AmbientLight('#a1a1a1', 0.2))
	let light2 = new THREE.DirectionalLight('#a1a1a1', 0.5)
	light2.position.set(-17.57, 9.398, -0.864)
	light2.target = model.getObjectByName('掘进机')
	scene.add(light2)
}

// 渲染逻辑
let requestAnimationFrameIndex
function render() {
	// 漫游
	keyType.value = cameraRender(objects)
	compassRotate(camera)
	// 运行动画
	mixers.forEach((mixer) => mixer.update(clock.getDelta()))
	// 视角动画
	TWEEN?.update()
	// 皮带动画
	model.getObjectByName('传送带贴图面1').material.map.offset.x += 0.01
	model.getObjectByName('传送带贴图面2').material.map.offset.y += 0.01
	// 煤块掉落动画
	// group.children.forEach((coal) => {
	//     coal.position.y -= 0.15 * coal.scale.x;
	//     if (coal.position.y < -8) {
	//         const scale = Math.random() * 0.8 + 0.2;
	//         coal.position.set(-Math.random(), Math.random() * 4, Math.random() * 3);
	//         coal.scale.set(scale, scale, scale);
	//         coal.rotateX(scale);
	//         coal.rotateY(scale);
	//         coal.rotateZ(scale);
	//     }
	// });
	renderer?.render(scene, camera)
	requestAnimationFrameIndex = requestAnimationFrame(render)
}
</script>

<style lang="scss" scoped>
.label {
	font-size: 30px;
	background: rgba(3, 15, 39, 0.6);
	border: 1px solid rgba(76, 107, 209, 0.5);
	width: 320px;
	position: absolute;
	z-index: 10;
	top: -50%;
	left: -50%;
	.val {
		font-weight: bold;
		font-size: 16px;
		color: #ffffff;
		text-shadow: 0px 1px 1px 0px rgba(4, 18, 42, 0.6);
	}
	.name {
		font-size: 12px;
		color: rgba(255, 255, 255, 0.6);
	}
}
</style>
